package com.docmanage.am.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.docmanage.am.domain.*;
import com.docmanage.am.domain.dto.AmDescriptionSearchDTO;
import com.docmanage.am.domain.dto.FileDTO;
import com.docmanage.am.domain.vo.AmDescriptionSearchVo;
import com.docmanage.am.domain.vo.FileVO;
import com.docmanage.am.mapper.AmDescriptionMapper;
import com.docmanage.common.config.MinioConfig;
import com.docmanage.common.enums.BorrowStatus;
import com.docmanage.common.utils.DateUtils;
import com.docmanage.common.utils.SecurityUtils;
import com.docmanage.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

import static com.docmanage.common.utils.SecurityUtils.isAdmin;
import static com.docmanage.common.utils.SecurityUtils.isArchivesAdmin;

/**
 * 档案著录Service接口
 *
 * @author docmanage
 * @date 2023-11-28
 */
@Service
public class AmDescriptionService {
    @Resource
    private AmDescriptionMapper amDescriptionMapper;
    @Resource
    private AmFolderService amFolderService;
    @Resource
    private AmGroupService amGroupService;
    @Resource
    private AmRoleDirectoryServiceImpl amRoleDirectoryService;

    @Resource
    private AmArchiveService amArchiveService;

    public Integer docNums() {
        Integer nums = amDescriptionMapper.docNums();
        return nums;
    }

    public List<AmFolder> folderNums() {
        List<AmFolder> level1 = new ArrayList<AmFolder>();

        List<AmDescriptionSearchVo> folderNums = amDescriptionMapper.selectAmDescriptionList(new AmDescriptionSearchDTO());
        Map<Long, Long> numMap = new HashMap<Long, Long>();
        if (!CollectionUtils.isEmpty(folderNums)) {
            for (AmDescriptionSearchVo descriptionSearchVo : folderNums) {
                if (!numMap.containsKey(descriptionSearchVo.getFolderId())) {
                    numMap.put(descriptionSearchVo.getFolderId(), 0L);
                }
                numMap.put(descriptionSearchVo.getFolderId(), numMap.get(descriptionSearchVo.getFolderId()) + 1L);
            }
        }

        Map<Long, List<AmFolder>> tree = new HashMap<Long, List<AmFolder>>();
        List<AmFolder> list = amFolderService.selectAmFolderList(new AmFolder());
        if (!CollectionUtils.isEmpty(list)) {
            for (AmFolder amFolder : list) {
                if (!tree.containsKey(amFolder.getParentId())) {
                    tree.put(amFolder.getParentId(), new ArrayList<AmFolder>());
                }
                tree.get(amFolder.getParentId()).add(amFolder);
            }

            level1 = tree.get(1L);
            for (AmFolder amFolder : level1) {
                Long nums = getDeepNum(amFolder, tree, numMap);
                amFolder.setFileCount(nums);
            }
        }

        //List<AmFolder> folderNums = amDescriptionMapper.folderNums();

        return level1;
    }

    public Long getDeepNum (AmFolder amFolder, Map<Long, List<AmFolder>> tree, Map<Long, Long> numMap) {
        Long nums = null == numMap.get(amFolder.getId()) ? 0L : numMap.get(amFolder.getId());

        if (tree.containsKey(amFolder.getId())) {
            List<AmFolder> children = tree.get(amFolder.getId());
            for (AmFolder child : children) {
                Long num = getDeepNum(child, tree, numMap);
                nums +=num;
            }
        }
        return nums;
    }

    /**
     * 查询档案著录
     *
     * @param id 档案著录主键
     * @return 档案著录
     */
    public AmDescription selectAmDescriptionById(Long id, Long roleId) {
        AmDescription amDescription = amDescriptionMapper.selectAmDescriptionById(id);
        amDescription.setBrStatusName(BorrowStatus.getNameByCode(amDescription.getBrStatus()).getName());
        if (null != amDescription.getFolderId()) {
            AmFolder amFolder = amFolderService.selectAmFolderById(amDescription.getFolderId());
            amDescription.setFolderName(null == amFolder ? "" : amFolder.getName());
        }
        if (null != amDescription.getGroupId()) {
            AmGroup amGroup = amGroupService.selectAmGroupById(amDescription.getGroupId());
            amDescription.setGroupName(null == amGroup ? "" : amGroup.getName());
        }
        List<Long> dirIds = new ArrayList<>();
        if (null != roleId) {
            AmRoleDirectory amRoleDirectory = new AmRoleDirectory();
            amRoleDirectory.setRoleId(roleId);
            List<AmRoleDirectory> roleDirectories = amRoleDirectoryService.selectAmRoleDirectoryList(amRoleDirectory);
            for (AmRoleDirectory roleDirectorie : roleDirectories) {
                dirIds.add(roleDirectorie.getDirectoryId());
            }
        }
        //List<FileVO> list = amArchiveService.selectAmArchiveListByDescId(id);
        List<FileVO> list = amArchiveService.selectByDescIdAndDirIds(id, dirIds);
        list.forEach(item->{
            item.setDownloadUrl(item.getUrl());
            if(!item.getUrl().contains(MinioConfig.getCdn())){
                item.setDownloadUrl(MinioConfig.getCdn() + item.getUrl());
            }
        });
        amDescription.setFileVOS(list);
        return amDescription;
    }

    /**
     * 查询档案著录列表
     *
     * @param dto 档案著录
     * @return 档案著录
     */
    public List<AmDescriptionSearchVo> selectAmDescriptionList(AmDescriptionSearchDTO dto) {
        //如果不是admin用户，则只能查看自己创建的申请单
//        if(!isAdmin(SecurityUtils.getUserId())||!isArchivesAdmin()){
//            //单据拥有者
//            dto.setUserId(SecurityUtils.getUserId());
//        }
        List<AmDescriptionSearchVo> amDescriptionSearchVos = amDescriptionMapper.selectAmDescriptionList(dto);
        amDescriptionSearchVos.forEach(item->item.setBrStatusName(BorrowStatus.getNameByCode(item.getBrStatus()).getName()));
        return amDescriptionSearchVos;
    }


    /**
     * 查询档案著录列表
     *
     * @param dto 档案著录
     * @return 档案著录
     */
    public List<AmDescriptionSearchVo> getPersonAmDescriptionList(AmDescriptionSearchDTO dto) {
        //单据拥有者
        dto.setUserId(SecurityUtils.getUserId());
        List<AmDescriptionSearchVo> amDescriptionSearchVos = amDescriptionMapper.selectAmDescriptionList(dto);
        amDescriptionSearchVos.forEach(item->item.setBrStatusName(BorrowStatus.getNameByCode(item.getBrStatus()).getName()));
        return amDescriptionSearchVos;
    }
    /**
     * 新增档案著录
     *
     * @param amDescription 档案著录
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertAmDescription(AmDescription amDescription) {
        if (StrUtil.isBlank(amDescription.getArchivedType())){
            amDescription.setArchivedType("archived_file");
            amDescription.setStatus("recorded");
        }
        String username = SecurityUtils.getUsername();
        amDescription.setCreateBy(username);
        amDescription.setUpdateBy(username);
        amDescription.setUserId(SecurityUtils.getUserId());
        amDescription.setDepId(SecurityUtils.getDeptId());
        List<FileVO> fileVOS = amDescription.getFileVOS();
        int i = amDescriptionMapper.insertAmDescription(amDescription);
        if (CollUtil.isEmpty(fileVOS)) {
            return i;
        }
        amDescription.setFileVOS(fileVOS);
        //档案文件绑定
        int j = amArchiveService.insertAmArchiveList(amDescription);
        if (j==fileVOS.size()){
            return i;
        }
        throw new RuntimeException();

    }

    /**
     * 修改档案著录
     *
     * @param amDescription 档案著录
     * @return 结果
     */
    public int updateAmDescription(AmDescription amDescription) {
        amDescription.setUpdateTime(DateUtils.getNowDate());
        amDescription.setUpdateBy(SecurityUtils.getUsername());
        List<FileVO> fileVOS = amDescription.getFileVOS();
        int i = amDescriptionMapper.updateAmDescription(amDescription);
        if (i > 0 && !CollUtil.isEmpty(fileVOS)) {
            //删除列表中相同的数据 通过description_id
            List<FileVO> list = amArchiveService.selectAmArchiveListByDescId(amDescription.getId());
            fileVOS.removeAll(list);
            //过滤掉已经添加过的文件
            List<FileVO> fileVOList = fileVOS.stream().filter(item -> item.getFileId() == null).collect(Collectors.toList());
            if (CollUtil.isEmpty(fileVOList)) {
                return i;
            }
            amDescription.setFileVOS(fileVOList);
            amArchiveService.insertAmArchiveList(amDescription);
        }
        return i;
    }

    /**
     * 批量删除档案著录
     *
     * @param ids 需要删除的档案著录主键
     * @return 结果
     */

    public int deleteAmDescriptionByIds(Long[] ids) {
        int i = amDescriptionMapper.deleteAmDescriptionByIds(ids);
        if (i > 0) {
            amArchiveService.deleteAmArchiveByDescriptionIds(ids);
        }
        return i;
    }

    /**
     * 删除档案著录信息
     *
     * @param id 档案著录主键
     * @return 结果
     */
    public int deleteAmDescriptionById(Long id) {
        int i = amDescriptionMapper.deleteAmDescriptionById(id);
        if (i > 0) {

            amArchiveService.deleteAmArchiveByDescriptionId(id);
        }
        return i;
    }
}
